package com.stefan.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Component
public class CitiNewsServiceImpl {
    private final static String NEWS_KEY_PREFIX = "news:";
    private final static DateTimeFormatter FORMATER = DateTimeFormatter.ofPattern("yyyyMMdd");; // 假设每个用户最多收藏10条新闻
    @Autowired
    private RedisTemplate redisTemplate;

    public void addNews(List<String> news) {
        // 将新闻添加到用户的收藏列表中
        LocalDate today = LocalDate.now();
        LocalDate sevenDaysAgo = today.minusDays(7);
        String formatDate = FORMATER.format(today);
        for (int i = 1; i <= news.size(); i++) {
            redisTemplate.opsForZSet().add(NEWS_KEY_PREFIX+formatDate, news.get(i - 1), i);
        }
        //delete 7天以上的key
        if (redisTemplate.hasKey(NEWS_KEY_PREFIX+FORMATER.format(sevenDaysAgo))) {
            redisTemplate.delete(NEWS_KEY_PREFIX+FORMATER.format(sevenDaysAgo));
        }
    }
    public HashSet<String> getNews() {
        // 获取用户收藏列表中的所有新闻
        LocalDate today = LocalDate.now();
        String formatDate = FORMATER.format(today);
        return (HashSet<String>) redisTemplate.opsForZSet().range(NEWS_KEY_PREFIX + formatDate, 0, -1);
    }
    public HashSet getNewsWithScores() {
        // 获取用户收藏列表中的所有新闻
        LocalDate today = LocalDate.now();
        String formatDate = FORMATER.format(today);
        Set set = redisTemplate.opsForZSet().rangeWithScores(NEWS_KEY_PREFIX + formatDate, 0, -1);
        return (HashSet) set;
    }
}
